import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart' as dio;

import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/entity/user_entity.dart';
import 'package:qianyi/pages/home/community/page_view/like/mock.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:dart_mock/dart_mock.dart' as mock;
import 'dart:io'; // 导入dart:io库以使用File类

import '../../../../entity/mine/User.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_entity.dart';
import '../../../../network/http_manager.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../view_model/mine/user_view_model.dart';

class EditUser extends StatefulWidget {
  const EditUser({Key? key}) : super(key: key);

  @override
  State<EditUser> createState() => _MineFansState();
}

class _MineFansState extends State<EditUser> {
  List<MockLike> lists = [];
  final picker = ImagePicker();
  XFile? xFile;
  TokenController tokenController = Get.find();
  TextEditingController textEditingController = TextEditingController();
  TextEditingController textEditingController1 = TextEditingController();
  final FocusNode focusNode = FocusNode();
  final FocusNode focusNode1 = FocusNode();

  @override
  void initState() {
    super.initState();

    setState(() {
      lists = MockLike.get();
    });
  }
  User? userEntity;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      bottomNavigationBar: BottomAppBar(
        child:  PreferredSize(
          preferredSize: Size.fromHeight(30),
          child:    MaterialButton(onPressed: (){
            tokenController.clear();

          },child: Text("退出登录"),),
        ) ,
      ),
      appBar: AppBar(
        title: Text("编辑用户"),

      ),
      body: GestureDetector(
        onTap: (){
          focusNode.unfocus();
          focusNode1.unfocus();
        },
        child: ChangeNotifierProvider(
            create: (BuildContext context) => UserViewModel(),
            child: Consumer<UserViewModel>(
                builder: (context, viewModel, child) {
                  List list = viewModel.datas;
                  return CustomRefresh(
                    physics: NeverScrollableScrollPhysics(),
                    isMaterialHeader:true,
                    controller: viewModel.refreshController,
                    enablePullUp: false,
                    enablePullDown: true,
                    onRefresh: () async {
                      viewModel.onRefresh();
                    },
                    onLoading: () async {
                      viewModel.onLoading();
                    },
                    child: viewModel.userEntity!=null?
                    Padding(padding: EdgeInsets.all(10),
                      child: ListView(
                        children: [
                          xFile!=null?
                          Image.file(
                            File(xFile!.path),
                            height: 300,
                            width: 300,
                            fit: BoxFit.cover,
                          ):
                          FancyShimmerImage(imageUrl: viewModel.avatar!),

                          SizedBox(height: 8,),

                          SizedBox(
                              child:  Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  MaterialButton(
                                    onPressed: () async {

                                      xFile = await picker.pickImage(source: ImageSource.gallery, maxHeight: 1080, maxWidth: 1080);
                                      File oriFile = new File(xFile!.path);
                                      // 2. compress file and get file.
                                      HudUtil.showBeautiful(context);
                                      var result = await FlutterImageCompress.compressWithFile(
                                          xFile!.path, quality: 80);

                                      String fileNameWithExtension = xFile!.path
                                          .split('/')
                                          .last;
                                      // String fileName = fileNameWithExtension.split('.').first;
                                      String _title = fileNameWithExtension;

                                      Uint8List uint8List = result!;
                                      Digest fileMd5 = md5.convert(
                                          oriFile.readAsBytesSync().sublist(1024, 5024));

                                      // String urlString = "${getBaseUrlMap()[BaseUrl.development]}"+'/api/util/fileoss//upload/checkfile?fileMd5=${fileMd5.toString()}';
                                      HttpEntity h = await HttpManager.getInstance().request(
                                          url: "/util/fileoss/upload/checkfile?fileMd5=${fileMd5.toString()}",
                                          method: Method.get) as HttpEntity;

                                      String pathAndUrl = h.getOriData()["data"];
                                      if (pathAndUrl.length == 0) {
                                        Map<String, dynamic> params1 = {
                                          'file': dio.MultipartFile.fromBytes(
                                              uint8List!, filename: 'image_}.png'),
                                          'fileMd5': fileMd5
                                        };
                                        HttpEntity h8 = await HttpManager.getInstance().request(
                                            url: '/util/fileoss/uploadOssVideoCover',
                                            method: Method.file,
                                            params: params1) as HttpEntity;
                                        // this.cover = h8.getOriData()['data'];
                                        // this.imgsUrl.add(this.cover);
                                        // 按钮点击事件
                                        User u = tokenController.user.value.first;
                                        u.avatar = h8.getOriData()['data'];
                                        Map<String,String> params = {
                                          "user":jsonEncode(u)
                                        };
                                        HttpEntity h2 = await HttpManager.getInstance().request(url: "/platform/user/updateUser",
                                            method: Method.post,params: params,object: params["user"]) as HttpEntity;
                                        HudUtil.dismiss();
                                        tokenController.updateUser();
                                        Navigator.pop(context);

                                      }},
                                    elevation: 0,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8), // 设置圆角
                                      side: BorderSide( // 设置边框
                                        color: WcaoTheme.placeholder, // 边框颜色
                                        width: 1.0, // 边框宽度
                                      ),
                                    ),

                                    color: Colors.white, // 设置按钮颜色
                                    // padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), // 设置内边距
                                    child: Text(
                                      "更换头像",
                                      style: TextStyle(

                                        fontSize: 18, // 设置文字大小
                                      ),
                                    ),
                                  )

                                  ,




                                ],
                              )
                          ),
                          FancyShimmerImage(imageUrl: tokenController!.cover.value),

                          SizedBox(height: 8,),

                          SizedBox(
                              child:  Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  MaterialButton(
                                    onPressed: () async {

                                      xFile = await picker.pickImage(source: ImageSource.gallery, maxHeight: 1080, maxWidth: 1080);
                                      File oriFile = new File(xFile!.path);
                                      // 2. compress file and get file.
                                      HudUtil.showBeautiful(context);
                                      var result = await FlutterImageCompress.compressWithFile(
                                          xFile!.path, quality: 80);

                                      String fileNameWithExtension = xFile!.path
                                          .split('/')
                                          .last;
                                      // String fileName = fileNameWithExtension.split('.').first;
                                      String _title = fileNameWithExtension;

                                      Uint8List uint8List = result!;
                                      Digest fileMd5 = md5.convert(
                                          oriFile.readAsBytesSync().sublist(1024, 5024));

                                      // String urlString = "${getBaseUrlMap()[BaseUrl.development]}"+'/api/util/fileoss//upload/checkfile?fileMd5=${fileMd5.toString()}';
                                      HttpEntity h = await HttpManager.getInstance().request(
                                          url: "/util/fileoss/upload/checkfile?fileMd5=${fileMd5.toString()}",
                                          method: Method.get) as HttpEntity;

                                      String pathAndUrl = h.getOriData()["data"];
                                      if (pathAndUrl.length == 0) {
                                        Map<String, dynamic> params1 = {
                                          'file': dio.MultipartFile.fromBytes(
                                              uint8List!, filename: 'image_}.png'),
                                          'fileMd5': fileMd5
                                        };
                                        HttpEntity h8 = await HttpManager.getInstance().request(
                                            url: '/util/fileoss/uploadOssVideoCover',
                                            method: Method.file,
                                            params: params1) as HttpEntity;
                                        // this.cover = h8.getOriData()['data'];
                                        // this.imgsUrl.add(this.cover);
                                        // 按钮点击事件
                                        User u = tokenController.user.value.first;
                                        u.cover = h8.getOriData()['data'];
                                        Map<String,String> params = {
                                          "user":jsonEncode(u)
                                        };
                                        HttpEntity h2 = await HttpManager.getInstance().request(url: "/platform/user/updateUser",
                                            method: Method.post,params: params,object: params["user"]) as HttpEntity;
                                        HudUtil.dismiss();
                                        tokenController.updateUser();
                                        Navigator.pop(context);

                                      }},
                                    elevation: 0,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8), // 设置圆角
                                      side: BorderSide( // 设置边框
                                        color: WcaoTheme.placeholder, // 边框颜色
                                        width: 1.0, // 边框宽度
                                      ),
                                    ),

                                    color: Colors.white, // 设置按钮颜色
                                    // padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), // 设置内边距
                                    child: Text(
                                      "更换封面",
                                      style: TextStyle(

                                        fontSize: 18, // 设置文字大小
                                      ),
                                    ),
                                  )

                                  ,




                                ],
                              )
                          ),
                          TextField(
                            focusNode: focusNode,
                            maxLength: 50,
                            minLines:3,
                            controller: textEditingController,
                            decoration: InputDecoration(
                              hintText: '${viewModel.userEntity!.description==null?'修改你的简介':viewModel.userEntity!.description}',
                              border: InputBorder.none,
                            ),
                            onEditingComplete: () {

                            },
                            onChanged: (e) {
                              // this.content = e;
                            },
                            onSubmitted: (e) {},
                            onTap: () {

                            },
                            maxLines: null,
                          ),
                          SizedBox(
                              child:  Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  MaterialButton(
                                    onPressed: () async {
                                      if(textEditingController.text.length <=0) {
                                        return;
                                      }
                                      HudUtil.showBeautiful(context);
                                      User u = tokenController.user.value[0];
                                      u.description = textEditingController.text;
                                      Map<String,String> params = {
                                        "user":jsonEncode(u)
                                      };
                                      HttpEntity h2 = await HttpManager.getInstance().request(url: "/platform/user/updateUser",
                                          method: Method.post,params: params,object: params["user"]) as HttpEntity;
                                      // 按钮点击事件

                                      tokenController.updateUser();
                                      HudUtil.dismiss();
                                      Navigator.pop(context);
                                    },
                                    elevation: 0,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8), // 设置圆角
                                      side: BorderSide( // 设置边框
                                        color: WcaoTheme.placeholder, // 边框颜色
                                        width: 1.0, // 边框宽度
                                      ),
                                    ),

                                    color: Colors.white, // 设置按钮颜色
                                    // padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), // 设置内边距
                                    child: Text(
                                      "更换简介",
                                      style: TextStyle(

                                        fontSize: 18, // 设置文字大小
                                      ),
                                    ),
                                  )

                                  ,




                                ],
                              )
                          ),
                          TextField(
                            focusNode: focusNode1,

                            maxLength: 10,
                            minLines: 1,
                            controller: textEditingController1,
                            decoration: InputDecoration(
                              hintText: '${viewModel.userEntity!.username==null?'修改你的昵称':viewModel.userEntity!.username}',
                              border: InputBorder.none,
                            ),
                            onEditingComplete: () {

                            },
                            onChanged: (e) {
                              // this.content = e;
                            },
                            onSubmitted: (e) {},
                            onTap: () {

                            },
                            maxLines: null,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [ MaterialButton(
                              onPressed: () async {
                                if(textEditingController1.text.length <=0) {
                                  return;
                                }
                                HudUtil.showBeautiful(context);
                                User u = tokenController.user.value[0];
                                u.username = textEditingController1.text;
                                Map<String,String> params = {
                                  "user":jsonEncode(u)
                                };
                                HttpEntity h2 = await HttpManager.getInstance().request(url: "/platform/user/updateUser",
                                    method: Method.post,params: params,object: params["user"]) as HttpEntity;
                                // 按钮点击事件

                                tokenController.updateUser();
                                HudUtil.dismiss();
                                Navigator.pop(context);
                              },
                              elevation: 0,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8), // 设置圆角
                                side: BorderSide( // 设置边框
                                  color: WcaoTheme.placeholder, // 边框颜色
                                  width: 1.0, // 边框宽度
                                ),
                              ),

                              color: Colors.white, // 设置按钮颜色
                              // padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), // 设置内边距
                              child: Text(
                                "更换昵称",
                                style: TextStyle(

                                  fontSize: 18, // 设置文字大小
                                ),
                              ),
                            )]
                            ,
                          )

                        ],
                      ),)

                        :Text(""),


                  );
                })
        ),
      )
      ,
    )

      ;
  }
}

Widget listCard(User user, UserViewModel viewModel) {
  final picker = ImagePicker();
  XFile? xFile;
  bool fav = mock.boolean();

  return Text("")


    ;
}
